﻿using sdk_cop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityPay.Core.DTO;
using UnityPay.Core.PayBase;

namespace UnityPay.Core.BankClass
{
    public class ICBC : BankBaseClass, BankPayActionInterface
    {
        /// <summary>
        /// 工商银行支付
        /// </summary>
        /// <param name="appid">工商银行APPID</param>
        /// <param name="priKey">工商银行私钥</param>
        /// <param name="apiwg">工商银行网关公钥</param>
        /// <param name="merid">商户号</param>
        public ICBC(string appid,string priKey,string apiwg,string merid)
        {
            this.APP_ID = appid;
            this.PriKey = priKey;
            this.PubKey = apiwg;
            this.MERCHANTID = merid;
            client = new DefaultIcbcClient(APP_ID, IcbcConstants.SIGN_TYPE_RSA2, PriKey, PubKey);
            this.Url = "https://gw.open.icbc.com.cn/";
        }

        /// <summary>
        /// 工商银行SDK
        /// </summary>
        DefaultIcbcClient client;

        
        public override string GetUrl()
        {
            return Url+UrlAction;
        }

        public string GetQrcodeType(string channel)
        {
            string qrcodetype = "";
            switch (channel)
            {
                case "91"://微信
                    qrcodetype = "2";
                    break;
                case "92"://支付宝
                    qrcodetype = "3";
                    break;
                case "93"://银联
                    qrcodetype = "4";
                    break;
                case "99"://工商银行支付
                    qrcodetype = "1";
                    break;
                case "94"://数字人民币
                    qrcodetype = "5";
                    break;
                default:
                    break;
            }
            return qrcodetype;
        }
        public string GetRESULT(string paystatus)
        {
            string RESULT;
            switch (paystatus)
            {
                case "-1"://下单失败
                    RESULT = "N";
                    break;
                case "0"://支付中
                    RESULT = "Q";
                    break;
                case "1"://支付成功
                    RESULT = "Y";
                    break;
                case "2"://支付失败
                    RESULT = "N";
                    break;
                case "3"://已撤销
                    RESULT = "N";
                    break;
                case "4"://撤销中请稍后查询
                    RESULT = "Q";
                    break;
                    
                default:
                    RESULT = "U";
                    break;
            }
            return RESULT;
        }
        /// <summary>
        /// 工商银行支付
        /// </summary>
        /// <param name="amount">元</param>
        /// <param name="qrcode">二维码</param>
        /// <param name="orderid">订单号</param>
        /// <param name="goodsname">商品名称</param>
        public BankMsgDTO Pay(string amount,string qrcode,string orderid,string goodsname="")
        {
            long amt = Convert.ToInt64( Convert.ToDouble(amount.Trim())*100);//元转分
            QrcodePayRequestV2 request = new QrcodePayRequestV2();
            QrcodePayRequestV2.QrcodePayRequestV2Biz bizContent = new QrcodePayRequestV2.QrcodePayRequestV2Biz();
            request.setServiceUrl("https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/pay/V2");
            bizContent.setQrCode(qrcode);
            bizContent.setMerId(this.MERCHANTID);
            bizContent.setOutTradeNo(orderid);
            bizContent.setOrderAmt(amt.ToString());
            bizContent.setTradeDate(DateTime.Now.ToString("yyyyMMdd"));
            bizContent.setTradeTime(DateTime.Now.ToString("HHmmss"));
            bizContent.setAttach($"{orderid}:{goodsname}");//该字段非必输项
            request.setBizContent(bizContent);

            QrcodePayResponseV2 response = null;
            try
            {
                response = (QrcodePayResponseV2)client.execute(request, "pay");
                BankMsgDTO dto;
                if (response.isSuccess())
                {

                    dto = new BankMsgDTO()
                    {
                         AMOUNT=response.getTotalAmt(),
                         ORDERID=response.getOutTradeNo(),
                         RESULT=GetRESULT(response.getPayStatus()),
                         WAITTIME="5",
                         ERRCODE=response.getReturnCode().ToString(),
                         ERRMSG=response.getReturnMsg().ToString(),
                         QRCODETYPE = GetQrcodeType( response.getChannel()),
                         TRACEID=response.getOrderId(),
                         WECHAT_NO= response.getTpOrderId(),
                         ZFB_NO=response.getTpOrderId(),
                    };

                }
                else
                {
                    dto = new BankMsgDTO()
                    {
                        AMOUNT = response.getTotalAmt(),
                        ORDERID = response.getOutTradeNo(),
                        RESULT = "N",
                        WAITTIME = "5",
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG = response.getReturnMsg().ToString(),
                        QRCODETYPE = GetQrcodeType(response.getChannel()),
                        TRACEID = response.getOrderId(),
                        WECHAT_NO = response.getTpOrderId(),
                        ZFB_NO = response.getTpOrderId(),
                    };
                }
                return dto;
            }
            catch (Exception e)
            {
                return new BankMsgDTO()
                {
                    RESULT = "N",
                    ERRMSG=e.Message,
                };
            }
        }

        public BankMsgDTO Query(string orderid, string qrcodetype="")
        {
            QrcodePayQueryRequestV2 request = new QrcodePayQueryRequestV2();
            QrcodePayQueryRequestV2.QrcodeQueryRequestV2Biz bizContent = new QrcodePayQueryRequestV2.QrcodeQueryRequestV2Biz();
            request.setServiceUrl("https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/paystatus/V2");
            bizContent.setMerId(this.MERCHANTID);
            bizContent.setOutTradeNo(orderid);
            request.setBizContent(bizContent);
            QrcodePayQueryResponseV2 response = null;
            try
            {
                response = (QrcodePayQueryResponseV2)client.execute(request, "msgId");
                BankMsgDTO dto;
                if (response.isSuccess())
                {
                    dto = new BankMsgDTO()
                    {
                        AMOUNT = (Convert.ToDouble(response.getTotalAmt()) / 100).ToString(),//分转元
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG = response.getReturnMsg(),
                        ORDERID = response.getOutTradeNo(),
                        TRACEID = response.getOrderId(),
                    };
                    //返回状态处理
                    switch (response.getPayStatus())
                    {
                        case "0":
                            dto.RESULT = "Q";
                            dto.ERRMSG = "支付中请稍后查询";
                            break;
                        case "1":
                            dto.RESULT = "Y";
                            dto.ERRMSG = "支付成功";
                            break;
                        case "2":
                            dto.RESULT = "N";
                            dto.ERRMSG = "支付失败";
                            break;
                        case "3":
                            dto.RESULT = "N";
                            dto.ERRMSG = "已撤销";
                            break;
                        case "4":
                            dto.RESULT = "Q";
                            dto.ERRMSG = "撤销中请稍后查询";
                            break;
                        case "5":
                            dto.RESULT = "Q";
                            dto.ERRMSG = "已全额退款";
                            break;
                        case "6":
                            dto.RESULT = "Q";
                            dto.ERRMSG = "已部分退款";
                            break;
                        case "7":
                            dto.RESULT = "Q";
                            dto.ERRMSG = "退款中请稍后查询";
                            break;
                        default:
                            dto.RESULT = "U";
                            dto.ERRMSG = "未知的状态";
                            break;
                    }
                    //返回渠道处理 QRCODETYPE 以及 第三方订单号处理
                    switch (response.getChannel())
                    {
                        case "91"://微信
                            dto.QRCODETYPE = "2";
                            dto.WECHAT_NO = response.getTpOrderId();
                            break;
                        case "92"://支付宝
                            dto.QRCODETYPE = "3";
                            dto.ZFB_NO= response.getTpOrderId();
                            break;
                        case "93"://银联
                            dto.QRCODETYPE = "4";
                            break;
                        case "94"://数字人民币
                            dto.QRCODETYPE = "5";
                            break;
                        case "99"://工商银行支付二维码
                            dto.QRCODETYPE = "1";
                            break;
                        default:
                            break;
                    }
                    
                    

                }
                else
                {
                    //失败
                    dto = new BankMsgDTO()
                    {
                        RESULT = "N",
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG=response.getReturnMsg()
                    };
                }
                return dto;
            }
            catch (Exception ex)
            {
                return new BankMsgDTO()
                {
                     RESULT="N",
                     ERRMSG=ex.Message,
                };
                
            }
        }
        #region 工商银行不支持的接口
        public BankMsgDTO ZfbWxQuery(string orderid, string qrcodetype)
        {
            throw new Exception("工商银行不支持支付宝、微信查询");
        }

        public BankMsgDTO ZfbWxOrderClose(string orderid, string qrcodetype)
        {
            throw new Exception("工商银行不支持支付宝、微信支付关闭");
        }

        public string Refund(string CUST_ID, string USER_ID, string PASSWORD, string orderid, string amount, string Refundid)
        {
            throw new Exception("工商银行不支持建行退款");
        }
        #endregion
        public BankMsgDTO IcbcRefund(string orderid, string amount, string Refundid)
        {

            QrcodePayReturnRequestV2 request = new QrcodePayReturnRequestV2();
            QrcodePayReturnRequestV2.QrcodePayReturnRequestV2Biz bizContent = new QrcodePayReturnRequestV2.QrcodePayReturnRequestV2Biz();
            request.setServiceUrl("https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/return/V2");
            bizContent.setRejectAmt(Convert.ToInt64((Convert.ToDouble(amount)*100)).ToString());
            bizContent.setMerId(this.MERCHANTID);
            bizContent.setOutTradeNo(orderid);
            bizContent.setRejectNo(Refundid);
            request.setBizContent(bizContent);
            QrcodePayReturnResponseV2 response;
            try
            {
                response = (QrcodePayReturnResponseV2)client.execute(request, "IcbcRefund");
                BankMsgDTO dto;
                if (response.isSuccess())
                {
                    if (response.getReturnCode()==0)
                    {
                        dto = new BankMsgDTO()
                        {
                            RESULT = "Y",
                            ERRCODE = response.getReturnCode().ToString(),
                            ERRMSG = response.getReturnMsg(),
                            AMOUNT = (Convert.ToDouble(response.getRealRejectAmt()) / 100).ToString(),
                        };
                    }
                    else
                    {
                        dto = new BankMsgDTO()
                        {
                            RESULT = "N",
                            ERRCODE = response.getReturnCode().ToString(),
                            ERRMSG = response.getReturnMsg(),
                            AMOUNT = (Convert.ToDouble(response.getRealRejectAmt()) / 100).ToString(),
                        };
                    }
                    //返回渠道处理 QRCODETYPE 以及 第三方订单号处理
                    switch (response.getOrderChannel())
                    {
                        case "91"://微信
                            dto.QRCODETYPE = "2";
                            break;
                        case "92"://支付宝
                            dto.QRCODETYPE = "3";
                            break;
                        case "93"://银联
                            dto.QRCODETYPE = "4";
                            break;
                        case "94"://数字人民币
                            dto.QRCODETYPE = "5";
                            break;
                        case "99"://工商银行支付二维码
                            dto.QRCODETYPE = "1";
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    //失败
                    dto = new BankMsgDTO()
                    {
                        RESULT = "N",
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG = response.getReturnMsg()
                    };
                }
                return dto;
            }
            catch (Exception ex)
            {
                return new BankMsgDTO()
                {
                    RESULT = "N",
                    ERRMSG = ex.Message,
                };
            }
        }

        public BankMsgDTO IcbcRefundQuery(string orderid, string Refundid)
        {
            QrcodePayReturnQueryRequestV2 request = new QrcodePayReturnQueryRequestV2();
            QrcodePayReturnQueryRequestV2.QrcodePayReturnQueryRequestV2Biz bizContent = new QrcodePayReturnQueryRequestV2.QrcodePayReturnQueryRequestV2Biz();
            request.setServiceUrl("https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/returnstatus/V2");
            bizContent.setMerId(this.MERCHANTID);
            bizContent.setOutTradeNo(orderid);
            bizContent.setRejectNo(Refundid);
            request.setBizContent(bizContent);
            QrcodePayReturnResponseV2 response;
            try
            {
                response = (QrcodePayReturnResponseV2)client.execute(request, "IcbcRefund");
                BankMsgDTO dto;
                if (response.isSuccess())
                {
                    dto = new BankMsgDTO()
                    {
                        RESULT = "Y",
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG = response.getReturnMsg(),
                        AMOUNT = (Convert.ToInt64(response.getRealRejectAmt()) / 100).ToString(),
                    };
                    //返回渠道处理 QRCODETYPE 以及 第三方订单号处理
                    switch (response.getOrderChannel())
                    {
                        case "91"://微信
                            dto.QRCODETYPE = "2";
                            break;
                        case "92"://支付宝
                            dto.QRCODETYPE = "3";
                            break;
                        case "93"://银联
                            dto.QRCODETYPE = "4";
                            break;
                        case "94"://数字人民币
                            dto.QRCODETYPE = "5";
                            break;
                        case "99"://工商银行支付二维码
                            dto.QRCODETYPE = "1";
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    //失败
                    dto = new BankMsgDTO()
                    {
                        RESULT = "N",
                        ERRCODE = response.getReturnCode().ToString(),
                        ERRMSG = response.getReturnMsg()
                    };
                }
                return dto;
            }
            catch (Exception ex)
            {
                return new BankMsgDTO()
                {
                    RESULT = "N",
                    ERRMSG = ex.Message,
                };
            }
        }
    }
}
